package com.lyy.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class logaspect {
    /*拿到日志记录器*/
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    /*
    * 定义一个切面,去拦截com.lyy.blog.web下所有的类的任意参数的方法
    * */
    @Pointcut("execution(* com.lyy.blog.web.*.*(..))")
    public void log(){

    }
    /*切面之前执行*/
    @Before("log() ")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String url=request.getRequestURL().toString();
        String ip=request.getRemoteAddr();
        String classmethod=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args=joinPoint.getArgs();
        //请求的日志包含ip，url，方法，参数
        resultlog resultlog=new resultlog(url,ip,classmethod,args);
        logger.info("request:{}",resultlog);
    }
    /*切面之后执行*/
    @After("log()")
    public void doAfter(){


        logger.info("------------------After");
    }
/*切面之后返回对象*/
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterreturn(Object result){

        logger.info("result:{} "+result);
    }
    private class resultlog{
        private String url;
        private String ip;
        private String classmethod;
        private Object[] args;

        public resultlog(String url, String ip, String classmethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classmethod = classmethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "resultlog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classmethod='" + classmethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
